<template>
  <base-breadcrumb :title="$route.meta.title">
    <!-- 职工代表大会编辑 -->
    <a-form-model ref="ruleForm" :model="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }" :rules="editModel != 0 ? rules : {}">
      <a-spin :spinning="loading">
        <!-- 表格 -->
        <a-card :bordered="false">
          <title-name title="基础信息"></title-name>
          <custom-form :isEmit="false" :formList="formList" :form="form" :editModel="editModel == 0 ? '' : ''"
          @selectOrg="selectOrg"> </custom-form>
        </a-card>
        <a-card :bordered="false">
          <a-row  :gutter="10">
            <a-col :span="4"  :style="'height: calc('+GET_REDRESS_PERCENTAGE+'vh - 250px); overflow-y: auto'">
              <div style="height: 100%;border-right: 1px solid rgba(215, 215, 215, 1);padding-right: 10px;width: 100%;overflow: hidden;box-sizing: border-box">
                <a-spin :spinning="loading2" style="height: 100%">
                  <a-input-search style="margin-bottom: 8px" placeholder="搜索" @change="onChange" />
                  <a-tree
                          :expanded-keys="expandedKeys"
                          :auto-expand-parent="autoExpandParent"
                          :tree-data="gData"
                          :selectedKeys.sync="selectedKeys"
                          :replaceFields="{children:'childList', title:'name', key:'id', value: 'id' }"
                          @expand="onExpand"
                          @select="selectTreeNode"
                          :style="'maxHeight: calc('+GET_REDRESS_PERCENTAGE+'vh - 320px);overflow: auto;'"
                  >
                    <template slot="title" slot-scope="{ name, status,bimNumber,id,childList}">
                      <div class="ellipsis" :title="name">
                                        <span v-if="name.indexOf(searchValue) > -1">
                                          {{ name.substr(0, name.indexOf(searchValue)) }}
                                          <span style="color: #f50">{{ searchValue }}</span>
                                          {{ name.substr(name.indexOf(searchValue) + searchValue.length) }}
                                        </span>
                        <span v-else>{{ name }}</span>
                        <span style="color: #ff4d4f">{{!status ? '（停用）': ''}}</span>
                        <a-tooltip v-if="!childList.length">
                          <template slot="title">{{ `${bimNumber > 0 ? '已' : '未'}关联${bimNumber > 0 ? bimNumber + '个' : ''}BIM模型` }}</template>
                          <a-badge
                            :numberStyle="{ fontSize: '10px', padding: '0 2px' }"
                            :count="bimNumber"
                            :overflow-count="9"
                          >
                            <a-icon
                              @click.stop="handleRelease(bimNumber,id)"
                              type="link"
                              style="margin: 4px"
                              :style="{ color: bimNumber > 0 ? '#1890ff' : '#ccc' }"
                            />
                          </a-badge>
                        </a-tooltip>
                      </div>
                    </template>
                    
                  </a-tree>
                  <div style="display: flex;justify-content: space-around;margin-top: 10px" v-if="hideBuquBtn()&&editModel != 0">
                    <a-button type="primary" @click="add" size="small" :disabled="!selectNode.status">添加</a-button>
                      <a-button type="primary" @click="edit" size="small" :disabled="!gData.length || isRoot">编辑</a-button>
                      <a-button  v-if="!selectNode.status" @click="updateNode" size="small" :disabled="!gData.length|| isRoot">启用</a-button>
                      <a-button type="danger" @click="updateNode" v-else size="small" :disabled="!gData.length|| isRoot">停用</a-button>
                  </div>
                </a-spin>
              </div>
            </a-col>
            <a-col :span="20">
              <title-name title="图纸目录清单"></title-name>
              <searchData :searchData="searchArr" :showTitleName="false" @search="search"></searchData>
              <a-button class="mb12" type="primary" icon="plus" v-if="editModel != 0" @click="handleOpen({drawId: ''})" :disabled="!form.projectId || isRoot ">新增</a-button>

              <ExcelImportButton v-if="editModel != 0" class="ml12" ref="excelImportButton" :disabled="!form.projectId || isRoot " icon="import" button-text="导入" @handleSubmit="handleImport" />
              <!-- 下载模板 -->
              <ExportExcel v-if="editModel != 0" class="ml12" ref="exportExcel" :export-list="exportList" icon="export" :file-name="'图纸目录清单模板.xlsx'" button-text="下载模板" />

              <excel ref="exportSelect" fileName="图纸目录清单标准模板导出" is-click-generate="false">
                <a-button
                        icon="download"
                        type="primary"
                        slot="excelBtn"
                        class="excelBtn"
                        :loading="loadingExport"
                        @click="exportSelect"
                >
              标准模板导出
                </a-button>
              </excel>
              <excel ref="exportAll" fileName="图纸目录清单全部导出" is-click-generate="false">
                <a-button
                        icon="download"
                        type="primary"
                        slot="excelBtn"
                        class="excelBtnAll"
                        :loading="loadingExport"
                        @click="exportAll"
                >
                 全部导出
                </a-button>
              </excel>
              <!-- 当type不是1（安检）显示按钮，当前节点选中且没有子级且不是根节点可操作 -->
              <!-- :disabled="!selectOptions || (selectOptions.childList && selectOptions.childList.length>0) || !selectOptions.parentId" -->
              <a-button
                v-if="selectOptions && selectOptions.parentId && selectOptions.childList && selectOptions.childList.length === 0"
                type="primary"
                icon="link"
                @click="
                  extraParams.subAreaId && delete extraParams.subAreaId
                  visibleBim = true
                "
              >
                关联BIM模型
              </a-button>
              <s-table ref="table" size="default" rowKey="drawId"
                       :rowSelection="rowSelection"
                       :defaultLoad="false"
                       :scroll="{ x: true }"
                       :columns="editModel != '0' ? columns : columnsLook" :data="loadData" :alert="true" show-size-changer show-quick-jumper>
            <span slot="versionDTOS" slot-scope="text, record">
              <a-select :disabled="editModel == '0'" placeholder="请选择类型" v-model="record.versionId" @change="changeVersion(record)" style="width: 110px;">
                <a-select-option v-for="(item, index) in record.versionDTOS" :key="index" :value="item.id">{{ item.businessVersion }}</a-select-option>
              </a-select>
            </span>
                <span slot="operation" slot-scope="text, record">
                  <MoreButton>
              <a
                      @click="
                  copyForm = record
                  copyForm.drawId = null
                  handleOpen(copyForm)
                "
              >复制</a
              >
                  <!-- 编辑 -->
              <span>
                <a-divider type="vertical" />
                <a @click="handleOpen(record)">编辑</a>
              </span>

                  <!-- 删除 -->
              <span v-if="record.versionId == null">
                <a-divider type="vertical"></a-divider>
                <a-popconfirm title="确定要删除?" @confirm="() => delDrawListItem(record)">
                  <a>删除</a>
                </a-popconfirm>
              </span>
                    </MoreButton>
            </span>
              </s-table>
            </a-col>
          </a-row>

        </a-card>
      </a-spin>
      <!-- 页脚操作栏 -->

      <div class="btn_box page-btn-right-top">
        <a-button @click="handleActiveClose">关闭</a-button>
      </div>
    </a-form-model>
     

    <a-modal v-model="nodeVisible"
             :title="nodeTitle"
             @ok="handleOk" okText="提交"
             width="650px"
             :confirmLoading="loadingBtn1">
      <a-form-model
              :model="form"
              :label-col="{ span: 4 }"
              :wrapper-col="{ span: 14 }"
      >
        <a-row>
          <a-col :span="12">
            <a-form-model-item label="父节点：">
              <a-input
                      disabled
                      v-model="formNode.parentName"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item  label="子节点：" class="requiredFormItem">
              <a-input
                      v-model="formNode.name" :maxLength="20" placeholder="请输入子节点"/>
            </a-form-model-item>
          </a-col>
<!--          <a-col :span="12">-->
<!--            <a-form-model-item label="状态：" class="requiredFormItem">-->
<!--              <a-select v-model="formNode.status" style="width: 120px" placeholder="请选择">-->
<!--                <a-select-option :value="1">-->
<!--                  可用-->
<!--                </a-select-option>-->
<!--                <a-select-option :value="0">-->
<!--                  不可用-->
<!--                </a-select-option>-->
<!--              </a-select>-->
<!--            </a-form-model-item>-->
<!--          </a-col>-->
        </a-row>

      </a-form-model>
    </a-modal>

    <!-- 表单弹窗 -->
    <dialog-form
      ref="dialogForm"
      :visible.sync="visible"
      editModel="E"
      :isEmit="false"
      :form="dialogForm"
      confirmBtn="确定"
      headerTitle="添加图纸目录清单"
      :width="900"
      :rules="rules"
      :formList="dialogList"
      @handleCancel="handleCancel"
      @confirm="submitForm"
    ></dialog-form>
       <!-- BIM模型列表弹窗 -->
       <BimView
      ref="bimView"
      :visible.sync="visibleBim"
      :zIndex="999"
      :extraParams="extraParams"
      @handleOpen="handleOpenBim"
    />
    <!-- 关联BIM模型弹窗 -->
    <BimRelease
      ref="bimRelease"
      :zIndex="1000"
      :destroyOnClose="true"
      :isRelease="!extraParams.subAreaId"
      :visible.sync="visibleRelease"
      :modelList="modelList"
      @confirm="handleBim"
    />
  </base-breadcrumb>
</template>

<script>
import { addDraw, updateDraw, getDraw, delDrawListItem, getProjectDraw, getIsProjectDraw, changeVersion, addDrawList, getDrawDetailList } from '@/api/technical/designFM'
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import SelectPersonModal from '@/components/SelectPersonModal'
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 分公司
import DialogForm from '@/components/DialogForm' // 弹窗表单
import Selector from '@/components/Select/Selector'
import ExportExcel from '@/components/exportExcel/ExportExcel' // 导出
import ExportResult from '@/components/Dialog/ExportResult' // 弹窗
import { queryProjectListByTree, createProjectList, majorTypeSelectListTree, editProjectList, projectListStatus } from "@/api/technology"
import {mapGetters } from 'vuex'
import BimView from '@/components/Dialog/BimView' // BIM模型关联列表
import BimRelease from '@/components/Dialog/BimRelease' // BIM模型关联
import { associateBimModel, getList } from '@/api/bimIntegrate/bimModel' // api
const columns = [
  {
    title: '序号',
    width: 80,
    dataIndex: 'index',
    customRender() {
      return arguments[2] + 1
    }
  },
  // {
  //   title: '工程部位/楼栋',
  //   dataIndex: 'projectLocation',
  //   width: 200,
  //   ellipsis: true
  // },
  {
    title: '专业类别',
    dataIndex: 'majorTypeName',
    width: 200,
    ellipsis: true
  },
  {
    title: '图纸类型',
    dataIndex: 'drawingTypeName',
    width: 200,
    ellipsis: true
  },
  {
    title: '图纸名称',
    dataIndex: 'name',
    width: 200,
    ellipsis: true
  },
  {
    title: '图号',
    dataIndex: 'drawNum',
    width: 100,
    ellipsis: true
  },
  {
    title: '版本号',
    dataIndex: 'versionDTOS',
    scopedSlots: { customRender: 'versionDTOS' }
  },
  {
    title: '收文时间',
    dataIndex: 'receiptDate',
    customRender() {
      return arguments[1].versionDTOS?.filter((i) => i.id == arguments[1].versionId)[0]?.receiptDate
    }
  },
  {
    title: '操作',
    dataIndex: 'operation',
    width: '120px',
    fixed: 'right',
    scopedSlots: { customRender: 'operation' }
  }
]
const columnsLook = [
  {
    title: '序号',
    width: 80,
    dataIndex: 'index',
    customRender() {
      return arguments[2] + 1
    }
  },
  // {
  //   title: '工程部位/楼栋',
  //   dataIndex: 'projectLocation',
  //   width: 200,
  //   ellipsis: true
  // },
  {
    title: '专业类别',
    dataIndex: 'majorTypeName',
    width: 200,
    ellipsis: true
  },
  {
    title: '图纸类型',
    dataIndex: 'drawingTypeName',
    width: 200,
    ellipsis: true
  },
  {
    title: '图纸名称',
    dataIndex: 'name',
    width: 200,
    ellipsis: true
  },
  {
    title: '图号',
    dataIndex: 'drawNum',
    width: 100,
    ellipsis: true
  },
  {
    title: '版本号',
    dataIndex: 'versionDTOS',
    width: 120,
    scopedSlots: { customRender: 'versionDTOS' }
  },
  {
    title: '收文时间',
    dataIndex: 'receiptDate',
    customRender() {
      return arguments[1].versionDTOS?.filter((i) => i.id == arguments[1].versionId)[0]?.receiptDate
    }
  }
]
const searchArr = [
  // {
  //   name: '工程部位楼栋',
  //   type: 'input',
  //   value: 'projectLocation'
  // },
  {
    name: '专业类别',
    type: 'tree-select',
    value: 'majorTypeId',
    attrs: {
      replaceFields: {children:'children', title:'majorName', key:'id', value: 'id' },
      showSearch: true,
      treeNodeFilterProp: 'title'
    },
    data: []
  },
  {
    name: '图纸类型',
    type: Selector,
    valueKey: 'drawingTypeId',
    selectType: '10',
    urlType: 'technical'
  },
  {
    name: '图纸名称',
    type: 'input',
    value: 'name'
  },
  {
    name: '图号',
    type: 'input',
    value: 'drawNum'
  },

  {
    name: '收文时间',
    type: 'dateRange',
    value: 'callNameDate',
    attr: {
      rangeFormat: ['receiptStartDate', 'receiptEndDate']
    }
  }
]
const getParentKey = (key, tree) => {
  if(!tree) return ''
  let parentKey;
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i];
    if (node.childList&&node.childList.length) {
      if (node.childList.some(item => item.id === key)) {
        parentKey = node.id;
      } else if (getParentKey(key, node.childList)) {
        parentKey = getParentKey(key, node.childList);
      }
    }
  }
  return parentKey;
};
export default {
  name: 'a' + Date.now(),
  extends: new BaseEditPage(),
  components: {
    SelectPersonModal,
    DialogForm,
    ExportResult,
    ExportExcel,
    BimView,
    BimRelease
  },
  data() {
    return {
      loadingExport: false,
      columns: columns,
      columnsLook:columnsLook,
      searchArr: searchArr,
      nodeVisible: false,
      nodeTitle: "添加节点",
      formNode: {
        level: "",
        name: "",
        status: null,
        parentId: '',
        parentName: '',
        projectId: '',
        branchComId: ''
      },
      loadingBtn1:false,
      loading2: false,
      loading: false, // 加载控件
      visible: false, //弹窗控件
      editModel: 0, // 操作状态:0 查看;1 编辑;2 新增
      form: { detailDTOS: [],curId: "", projectId:"", branchComId: '' }, // 表单
      id: '',
      loadingBtn: {
        DELETE: false,
        DRAFT: false,
        SUBMITTED: false,
        REJECTED: false
      },
      copyForm: {},
      dialogForm: {},
      rules: {
        projectLocation: [{ required: true, message: '请输入' }],
        majorTypeId: [{ required: true, message: '请选择' }],
        name: [{ required: true, message: '请输入' }],
        drawNum: [{ required: true, message: '请输入' }],
        plotDate: [{ required: true, message: '请选择' }],
        drawingTypeId: [{ required: true, message: '请选择' }]
      },
      queryParam: {},
      loadData: async (parameter) => {
        this.queryParam.branchComId = this.form.branchComId
        this.queryParam.projectId = this.form.projectId
        if (this.queryParam.branchComId && this.queryParam.projectId) {
          const requestParameters = Object.assign(parameter, {needCount: true},{query: {...this.queryParam,
                  projectListId: this.selectNode.id === '0' ? null : this.selectNode.id}})

          return getDrawDetailList(requestParameters).then((res) => {
            return res
          })
        }
      },

      init: false, // 初始化控件
      titles: ['图纸目录清单查看', '图纸目录清单编辑', '图纸目录清单新增'],
      importCheck: {
        // '工程部位/楼栋': 'projectLocation',
        专业类别: 'majorTypeName',
        图纸类型: 'drawingTypeName',
        图纸名称: 'name',
        图号: 'drawNum'
      },
      parentName: '',
      expandedKeys: [],
      selectNode: {},
      autoExpandParent: false,
      gData: [],
      selectedKeys: [],
      searchValue: "",
      isRoot: true,
      dataList: [],
      selectedRowKeys: [],
      selectedRows: [],
      selectOptions: {}, // 树选中节点对象
      modelList:[],
      visibleBim: false, // BIM模型列表弹窗控件
      visibleRelease: false, // BIM模型关联弹窗控件
    }
  },

  mounted() {
    this.$route.meta.title = ['图纸目录清单查看', '图纸目录清单编辑', '图纸目录清单新增'][this.editModel]
    // 不为添加时请求详情

    if (this.editModel != 2) {
      this.form.curId = this.$route.query.projectId
    } else {
      if(this.$userInfo().currentPost.code ==='PD') {
        this.form.curId = this.$userInfo().currentPost.id
      }
      this.$nextTick(() => {
        this.init = true
      })
    }
    this.$nextTick(()=>{
      this.$refs.exportSelect.tableToExcelFile({columns:[
          {
            title: '专业类别',
            dataIndex: 'majorTypeName',
          },
          {
            title: '图纸类型',
            dataIndex: 'drawingTypeName',
          },
          {
            title: '图纸名称',
            dataIndex: 'name',
          },
          {
            title: '图号',
            dataIndex: 'drawNum',
          },
        ]}, 0)
      this.$refs.exportAll.tableToExcelFile( { columns: [
          {
            title: '序号',
            width: 80,
            dataIndex: 'index'
          },
          // {
          //   title: '工程部位/楼栋',
          //   dataIndex: 'projectLocation',
          //   width: 200,
          //   ellipsis: true
          // },
          {
            title: '专业类别',
            dataIndex: 'majorTypeName',
          },
          {
            title: '图纸类型',
            dataIndex: 'drawingTypeName',
          },
          {
            title: '图纸名称',
            dataIndex: 'name',
          },
          {
            title: '图号',
            dataIndex: 'drawNum',
          },
          {
            title: '版本号',
            dataIndex: 'version',
          },
          {
            title: '收文时间',
            dataIndex: 'receiptDate'
          },
        ] },0)
    })
  },
  computed: {
    ...mapGetters(['GET_REDRESS_PERCENTAGE']),
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        selectedRows: this.selectedRows,   // 当前行所有数据
        onChange: this.onSelectChange
      }
    },
    exportList() {
      let list = this.$clone(this.columns)
      list.pop()
      list.pop()
      list.pop()
      list.shift()

      return [
        {
          columns: list,
          datas: [{}]
        }
      ]
    },
    dialogList() {
      return [
        // {
        //   type: 'BaseInput',
        //   span: 12,
        //   label: '工程部位/楼栋',
        //   keyName: 'projectLocation'
        // },
        {
          keyName: 'majorTypeId',
          label: '专业类别',
          type: 'ATreeSelect',
          span: 12,
          disabled: !!this.dialogForm.drawId,
          attrs: {
            replaceFields: {children:'children', title:'majorName', key:'id', value: 'id' },
            showSearch: true
          },
          data: this.searchArr[0].data
        },
        {
          keyName: 'drawingTypeId',
          label: '图纸类型',
          type: Selector,
          span: 12,
          disabled: !!this.dialogForm.drawId,
          attrs: {
            selectType: '10',
            urlType: 'technical'
          }
        },
        {
          type: 'BaseInput',
          span: 12,
          label: '图纸名称',
          keyName: 'name'
        },
        {
          type: 'BaseInput',
          span: 12,
          label: '图号',
          keyName: 'drawNum'
        }
      ]
    },
    formList() {
      return [
        {
          label: '所属单位',
          type: 'orgTree',
          keyName: 'curId',
          rules: [{ required: true, message: '请选择项目名称', trigger: 'change' }],
          span: 16,
          isAutoSelectFirst:true,
          isNeedAuth:true,
          checkStrictly: true,
          disabled:true,
          statusSet:[1,2,3,4,5,6],
          isQueryProjecDetail: false
        },
        // {
        //   type: SelectSubCompany,
        //
        //   keyName: 'branchComId',
        //   label: '分公司名称',
        //   disabled: true,
        //   attrs: {
        //     isDefaultSelected: this.editModel == 2,
        //     autoSelected: this.editModel == 2
        //   }
        // },
        // {
        //   type: SelectProject,
        //   keyName: 'projectId',
        //   label: '项目名称',
        //   disabled: true,
        //   attrs: {
        //     isDefaultSelected: this.editModel == 2,
        //     autoSelected: this.editModel == 2,
        //     keyValue: 'branchComId',
        //     isClear: this.editModel == 2,
        //     isEdit: this.editModel != 2,
        //     form: this.form
        //   },
        //   selectChange: (e) => {
        //     if (this.editModel == 2) {
        //       this.loading = true
        //       getProjectDraw({ id: e.code }).then((res) => {
        //         this.loading = false
        //         this.form = res.data
        //         this.id = res.data.id
        //         this.$refs.table.loadData()
        //       })
        //     }
        //   }
        // }
      ]
    },
    // 查看关联BIM模型列表请求参数
    extraParams() {
      return { projectId: this.form.projectId }
    }
  },
  methods: {
        /**
     * @description: 打开模型
     * @param {Array} data：模型列表或者模型选中项
     */
     handleOpenBim(data) {
      this.modelList = data
      this.visibleBim = false
      this.visibleRelease = true
    },
        /**
     * @description: BIM模型关联
     * @param {Array<Number>} floorIdList：关联楼层列表
     */
     handleBim(floorIdList, floorIdUuidList) {
      console.log(floorIdList,floorIdUuidList)
      this.$confirm({
        title: '提示',
        content: '确定要关联BIM模型吗？',
        onOk: () => {
          const args = {
            floorIdList,
            floorIdUuidList,
            modelId: this.modelList[0].id,
            subAreaId: this.selectedKeys[0]
          } // 关联参数
          return associateBimModel(args).then((res) => {
            if (res.code == 0 || res.data.code == 0) {
              this.$message.success('关联成功！')
              this.visibleRelease = false
              this.queryProjectListByTree(false)
            }
          })
        }
      })
    },
    exportAll() {
      this.queryParam.branchComId = this.form.branchComId
      this.queryParam.projectId = this.form.projectId
      if (this.queryParam.branchComId && this.queryParam.projectId) {
        const requestParameters = Object.assign({needCount: true,  pageSize: 99999, pageNo: 1},{query: {...this.queryParam,
            projectListId: this.selectNode.id === '0' ? null : this.selectNode.id}})
        getDrawDetailList(requestParameters).then((res) => {
          res.data.forEach((item, index) => {
            if(item.versionId) {
              let obj = item.versionDTOS.find(ele=>item.versionId === ele.id)
             if(obj) {
               item.version = obj.businessVersion
               item.receiptDate = obj.receiptDate
             } else {
               item.version = ""
               item.receiptDate = ""
             }

            }
            item.index = index+1
          })
          this.$refs.exportAll.setDataAndGenerate(res.data)
        })
      }
    },
    exportSelect() {
      this.queryParam.branchComId = this.form.branchComId
      this.queryParam.projectId = this.form.projectId
      if (this.queryParam.branchComId && this.queryParam.projectId) {
        const requestParameters = Object.assign({needCount: true, pageSize: 99999, pageNo: 1},{query: {...this.queryParam,
            projectListId: this.selectNode.id === '0' ? null : this.selectNode.id}})
         getDrawDetailList(requestParameters).then((res) => {
           this.$refs.exportSelect.setDataAndGenerate(res.data)
        })
      }

    },
    onSelectChange(keys, rows) {
      this.selectedRowKeys = keys
      this.selectedRows = rows
    },
    handleOk() {
      const data = {
        branchComId:  this.form.branchComId,
        projectId: this.form.projectId,
        level: this.formNode.id ? this.selectNode.level :  this.selectNode.level+1,
        name: this.formNode.name,
        parentId: this.formNode.id ? this.selectNode.parentId: this.selectNode.id,
        status: this.formNode.status
      }
      if(!this.formNode.name) {
        this.$message.warning("请输入子节点")
        return
      }
      // if(this.formNode.status === null) {
      //   this.$message.warning("请选择状态")
      //   return
      // }
      const api = [createProjectList, editProjectList][this.formNode.id ? 1 : 0]
      this.loadingBtn1 = true
      if(this.formNode.id ) {
        data.id = this.formNode.id
      }
      api(data).then(res=>{
        this.loadingBtn1 = false
        this.nodeVisible = false
        if(this.formNode.id ) {
          this.selectNode.level = this.selectNode.level + 1
          this.selectNode.name = this.formNode.name
        }
        this.queryProjectListByTree(false)
      }).catch(()=>{
        this.loadingBtn1 = false
      })
    },
    queryProjectListByTree(isInit=true) {
      this.loading2 = true
      const data = {
        branchComId:  this.form.branchComId,
        projectId: this.form.projectId
      }
      queryProjectListByTree(data).then((res)=>{
        this.generateList(res.data)
        this.gData = res.data
        this.loading2 = false
        if(isInit) {
          this.selectNode = this.gData[0]
          this.selectedKeys = [this.gData[0].id]
          this.$nextTick(()=>{
            this.$refs.table.refresh(true)
          })
        }
        this.selectOptions = this.findIdData(this.gData,this.selectedKeys);
      }).catch(()=>{
        this.loading2 = false
      })
    },
    generateList(data) {
      for (let i = 0; i < data.length; i++) {
        const node = data[i];
        node.scopedSlots = { title: 'title'}
        this.dataList.push(node);
        if (node.childList&&node.childList.length>0) {
          this.generateList(node.childList);
        }
      }
    },
    add() {
      if(this.selectNode.bimNumber > 0) {
        this.$message.warning('该节点已关联BIM模型,不能进行添加')
        return
      }
      this.formNode = {
                name: "",
                status: null,
                parentName: this.selectNode.name
      }
      this.nodeTitle = '添加节点'
      this.nodeVisible = true
    },
    updateNode() {
      this.formNode.id = this.selectNode.id
      const data = {
        branchComId:  this.form.branchComId,
        projectId: this.form.projectId,
        level: this.selectNode.level,
        name: this.selectNode.name,
        id: this.selectNode.id == '0' ? null : this.selectNode.id,
        parentId: this.selectNode.parentId,
        status: this.selectNode.status ? 0 : 1
      }
      projectListStatus(data).then(res=>{
        this.selectNode.status = this.selectNode.status ? 0 : 1
        this.queryProjectListByTree(false)
      })
    },
    edit() {
      this.formNode.parentName = this.parentName
      this.formNode.name = this.selectNode.name
      this.formNode.status = this.selectNode.status ? 1 : 0
      this.formNode.id = this.selectNode.id
      this.nodeTitle = '修改节点'
      this.nodeVisible = true
    },
    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys;
      this.autoExpandParent = false;
    },
    selectTreeNode(selectedKeys, { node}) {
      this.selectedKeys = selectedKeys;
      this.selectOptions = this.findIdData(this.gData,this.selectedKeys);
      this.selectNode = {...node.dataRef}
      if(!node.dataRef.parentId) {
        this.isRoot = true
      } else {
        this.isRoot = false
        this.parentName = node.$parent.dataRef.name
      }
      this.$refs.table.refresh(true)
    },
  findIdData(data, id) {  //根据id找到对应的值
      for (let i = 0; i < data.length; i++) {
        let item = data[i];
        if (item.id == id) {
          return item;
        } else {
          if (item.childList && item.childList.length > 0) {
            let res = this.findIdData(item.childList, id);
            if (res) return res;
          }
        }
      }
    },
    onChange(e) {
      const value = e.target.value;
      const expandedKeys = this.dataList
              .map(item => {
                if (item.name.indexOf(value) > -1) {
                  console.log(item.id)
                  return getParentKey(item.id, this.gData);
                }
                return null;
              })
              .filter((item, i, self) => item && self.indexOf(item) === i);
      console.log(expandedKeys,'expandedKeys')
      Object.assign(this, {
        expandedKeys,
        searchValue: value,
        autoExpandParent: true,
      });
    },
    majorTypeSelectListTree() {
      majorTypeSelectListTree( this.form.projectId).then(res=>{
        res.data.forEach(item=>{
          item.majorName = item.programmeName
          item.disabled = true
        })
          this.searchArr[0].data = res.data
      })
    },
    selectOrg(val) {
      if(val.length&&val.length < 2) {
        this.form.branchComId = val[val.length - 1].orgId
      } else if(val.length >= 2 ) {
        this.form.branchComId = val[val.length - 2].orgId
        this.form.projectId = val[val.length - 1].projectId
        this.majorTypeSelectListTree()
        this.queryProjectListByTree()
            if (this.editModel != 2) {
              this.loading = false
              // getProjectDraw({ id: this.form.projectId }).then((res) => {
              //   this.loading = false
              //   this.form = {...this.form, ...res.data}
              //   this.id = res.data.id
              //   this.$refs.table.loadData()
              // })
            }
      }
    },
    /**
     * 导入
     */
    handleImport(e) {
      let form = []
      let that = this
      let messages = []
      console.log(e)
      for (let m in e) {
        let keys = e[m]
        let listItem = {}
        let msg = `第${Number(m) + 1}行：`
        let msgList = []
        // 校验excel的表头数量
        // console.log(e[m],e[m][index])
        // 校验excel的表头字段
        for (let i in this.importCheck) {
          let item = this.importCheck[i]
          if (!keys[i] && !Object.keys(keys).includes(i)) {
            msgList.push(`${i.replace(/\*/g, '')}不能为空`)
          } else {
            listItem[item] = (keys[i] || '') + ''
          }
        }

        msgList.length > 0 && messages.push(<div>{msg + msgList.join('，')}</div>)
        form.push(listItem)
      }
      console.log(form)
      if (messages.length > 0) {
        that.loadingImport = false
        let content = messages.map((item) => <div style="width:100%">{item}</div>)
        that.$warning({
          width: 800,
          title: '导入失败',
          content: content
        })
        return
      }
      if (form.length > 0) {
        form.forEach(item=>{
          item.branchComId = this.form.branchComId
          item.projectId = this.form.projectId
          item.projectListId = this.selectNode.id
        })
        let pram = {
          projectId : this.form.projectId,
          param: form
        }
        addDrawList(pram).then((res) => {
          this.$refs.table.refresh(true)
        })
      }

      //   this.form.commercialInsertDetaileds = this.form.commercialInsertDetaileds.concat(form)
      //   this.$refs.table.refresh(true)
    },
    //搜索
    search(value) {
      value && (this.queryParam = value)
      this.$refs.table.refresh(true)
    },
    changeVersion(record) {
      const tagat = record.versionDTOS.filter((i) => i.id == record.versionId)[0]
      record.receiptDate = tagat.receiptDate

      this.loading = true

      let params = {
        id: record.versionId,
        detailId: record.drawId
      }
      changeVersion(params)
        .then((res) => {
          this.loading = false
          this.$message.success('版本修改成功')
        })
        .catch(() => {
          this.loading = false
        })
    },
    getDetails() {
      this.loading = true
      console.log(this.id)
      getDraw({ id: this.id })
        .then((res) => {
          this.loading = false

          this.form = res.data
          if(this.form.projectId) {
            this.form.curId =  this.form.projectId
          } else {
            this.form.curId =  this.form.branchComId
          }

          this.$refs.table.loadData()
          this.$nextTick(() => {
            this.init = true
          })
        })
        .catch(() => {
          this.loading = false
        })
    },

    handleOpen(e) {
      this.dialogForm = e
      this.dialogForm = { ...this.form, ...this.dialogForm }
      console.log(this.selectOptions,'222222222',this.selectedKeys)

      this.visible = true
    },
    delDrawListItem(e) {
      delDrawListItem({ id: e.drawId }).then((res) => {
        this.$refs.table.loadData()
      })
    },
    handleCancel() {
      this.form.drawId = ''
    },
    /**
     * 提交表单
     */
    async submitForm(e) {
      let that = this
      that.$refs.dialogForm.loading = true
      // if (!e.drawId) {
      //     let res = await getIsProjectDraw({ id: e.projectId, name: e.projectLocation })
      //     console.log(res.data.draw)
      //     if (!res.data.draw) {
      //         that.$message.warning('工程部位/楼栋名称不可重复')
      //         that.$refs.dialogForm.loading = false
      //         return
      //     }
      // }
      if(!e.drawId) {
        e.projectListId = this.selectNode.id
      }
      let api = e.drawId ? updateDraw : addDraw
      api(e)
        .then((res) => {
          that.$refs.dialogForm.loading = false
          that.$message.success((e.drawId ? '编辑' : '添加') + '成功！')
          that.visible = false
          that.id = res.data.id
          that.form.drawId = ''
          that.$refs.table.refresh(true)

        })
        .catch((res) => {
          that.$refs.dialogForm.loading = false
        })
    },
     /**
     * @description: 打开模型列表
     * @param {Object} data：节点数据
     */
     handleRelease(bimNumber,id) {
      if (bimNumber > 0) {
        this.extraParams.subAreaId = id
        // 关联数量大于1则打开模型列表，只有一个时则直接打开模型详情
        if (bimNumber > 1) {
          this.visibleBim = true
        } else {
          let args = { pageSize: 10, pageNum: 1, param: { projectId: this.form.projectId, subAreaId: id } }
       
          // 请求模型参数
          getList(args)
            .then((res) => {
              if (res.code === '0') {
                const record = res.data?.list?.[0]
                const params = [{ id: record.id, modelId: record.modelFileId, version: record.modelFileVersion, modelTitle: record.modelName }]
                this.handleOpenBim(params)
              }
            })
            .finally(() => {
    
            })
        }
      }
    },
  }
}
</script>

<style lang="less" scoped>
// /deep/ .ant-form-item {
//     .ant-form-item-label {
//         height: 28px;
//         width: 200px;
//         line-height: 22px;
//         padding: 6px 4px 0 0;
//         text-align: right;
//         white-space: pre-wrap;
//         overflow: visible;
//     }
//     .ant-form-item-control-wrapper {
//         width: calc(100% - 200px);
//     }
// }
// .file_prompt {
//     color: #999;
// }
</style>
